import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'

let timeout = 10000
const baseUrl = config.baseUrl

const request = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header['Authorization'] = 'Bearer ' + getToken()
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json'
		}).then(response => {
			const code = response.data.code || 200
			let msg = null;
			if (response.statusCode === 200) {
				if (response.data.code === 200) {
					resolve(response)
				} else if(response.data.code === 401) {
					uni.showModal({
						title: '温馨提示',
						content: '登录状态已过期，您可以继续留在该页面，或者重新登录?',
						success: function (res) {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/login/login'
								})
								uni.clearStorageSync();
							} else if (res.cancel) {
							}
						}
					})
				} else {
					msg = errorCode[response.data.code] || response.data.msg || errorCode['default'];
					uni.showToast({
						title: msg,
						icon: 'none',
						duration: 3000,
					})
				}
			} else {
				msg = '后端接口连接异常';
				uni.showToast({
					title: msg,
					icon: 'none',
					duration: 3000,
				})
			}
		}).catch(error => {
			let message = error.errMsg;
			if (message === 'Network Error') {
				uni.showToast({
					title: '后端接口连接异常',
					icon: 'none',
					duration: 3000
				})
			} else if (message === 'request:fail timeout') {
				uni.showToast({
					title: '系统接口请求超时',
					icon: 'none',
					duration: 3000
				})
			} else if (message === 'request:fail ') {
				uni.showToast({
					title: '网络错误',
					icon: 'none',
					duration: 3000
				})
			}
		})
	})
}

export default request